//
//  OAuthViewController.swift
//  xinlangweibo
//
//  Created by 陈志强 on 15/11/11.
//  Copyright © 2015年 陈志强. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
class OAuthViewController: UIViewController {
//    let client_id = "510842630"
//    let redirect_uri = "http://www.itcast.cn"
//    let client_secret = "94e17957ad893974a3dc3cc2cc94953d"

    let webView = UIWebView()
    
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount(){
        let jsString = "document.getElementById('userId').value = '15003880784' , document.getElementById('passwd').value = 'chen847733306';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
//    private func setUpUI(){
//        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
//    }
    private func  loadOauthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
    }
    
    
    private func setUpUI(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title:"自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        loadOauthPage()
        setUpUI()
        // Do any additional setup after loading the view.
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }

}
extension OAuthViewController: UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri){
            return false
        }
        guard let query = request.URL?.query else{
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        print(code)
        //loadAssesToken(code)
        UserAccountViewModel().loadAssesToken(code){(error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("网络君正在睡觉,请稍后再来")
                return
            }
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "welcom")
            })
            //self.dismissViewControllerAnimated(true, completion: nil)
        }
        return false
    }
    
//    private func loadAssesToken(code: String){
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        let parameters = ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
//        let AFN = AFHTTPRequestOperationManager()
//        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        AFN.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//            if let dict = result as? [String: AnyObject]{
//                let account = UserAccount(dict:dict)
////                print(dict)
////                print(account)
//                self.loadUserInfo(account)
//            }
//            
//            }) { (_, error) -> Void in
//                print(error)
//        }
//    }
//    private func loadUserInfo(account: UserAccount){
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        //print(account.access_token)
//        let parmaters = ["access_token": account.access_token!, "uid": account.uid!]
//        
//        let AFN = AFHTTPRequestOperationManager()
//        AFN.GET(urlString, parameters: parmaters, success: { (_, result) -> Void in
//            if let dict = result as? [String : AnyObject] {
//                account.avatar_large = dict["avatar_large"] as? String
//                account.name = dict["name"] as? String
//                
////                account.saveAccount()
//            }
//            }) { (_, error) -> Void in
//                print(error)
//        }
//
//    }
}
